﻿#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


//使⽤qsort函数排序整型数据
//int int_cmp(const void* p1, const void* p2)
//{
//	return *(int*)p1 - *(int*)p2;
//}
//
//void test1()
//{
//	int arr[10] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
//	int sz = sizeof(arr) / sizeof(arr[0]);
//	qsort(arr, sz, sizeof(int), int_cmp);
//	for (int i = 0; i < sz; i++)
//	{
//		printf("%d ", arr[i]);
//	}
//}

//使⽤qsort排序结构数据
//struct stu
//{
//	char name[20];
//	int age;
//};
//
//int stu_cmp_by_age(const void* p1, const void* p2)
//{
//	return ((struct stu*)p1)->age - ((struct stu*)p2)->age;
//}
//
//int stu_cmp_by_name(const void* p1, const void* p2)
//{
//	return strcmp(((struct stu*)p1)->name, ((struct stu*)p2)->name);
//}
//
//void test2()
//{
//	struct stu s[] = { {"zhangsan",20},{"lisi",30}, {"wangwu",18}};
//	int sz = sizeof(s) / sizeof(s[0]);
//	qsort(s, sz, sizeof(s[0]), stu_cmp_by_age);
//}

// qsort函数的模拟实现,以冒泡排序为底层
void Swap(char* p1, char* p2, size_t size)
{
	for (int i = 0; i < size; i++)
	{
		char tep = *p1;
		*p1 = *p2;
		*p2 = tep;
		p1++;
		p2++;
	}
}

int int_cmp(const void* p1, const void* p2)
{
	return *(int*)p1 - *(int*)p2;
}


void bubble_qsort(void* base, size_t sz, size_t	size, int (*cmp)(const void* p1, const void* p2))
{
	for (int i = 0; i < sz - 1; i++)
	{
		for (int j = 0; j < sz - 1 - i; j++)
		{
			if (cmp((char*)base + j * size, (char*)base + (j + 1) * size) > 0)
			{
				Swap((char*)base + j * size, (char*)base + (j + 1) * size, size);
			}
		}
	}
}

void test3()
{
	int arr[10] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	bubble_qsort(arr, sz, sizeof(int), int_cmp);
	for (int i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
}

int main()
{
	//test1();

	//test2();

	test3();
	return 0;
}